package sunyu.kit.mina;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import sunyu.kit.common.LogKit;
import sunyu.kit.common.StringKit;

import java.net.InetSocketAddress;

public class SocketClient extends IoHandlerAdapter {
    private static final Logger logger = LogKit.getLogger();
    private static IoSession session;
    private IoConnector connector;

    public SocketClient(String host, int port) {
        connector = new NioSocketConnector();
        connector.setHandler(this);
        ConnectFuture connFuture = connector.connect(new InetSocketAddress(host, port));
        connFuture.awaitUninterruptibly();
        session = connFuture.getSession();
        logger.debug("TCP 客户端启动,连接到主机：{} 端口：{}", host, port);
    }

    public static IoSession getSession() {
        return session;
    }

    public static void sendBytes(byte[] bytes) {
        IoBuffer buffer = IoBuffer.allocate(20);
        // 自动扩容
        buffer.setAutoExpand(true);
        byte[] realtimemsg = bytes;
        buffer.put(realtimemsg);
        buffer.flip();
        session.write(buffer);
    }

    public static void main(String[] args) throws InterruptedException {
        SocketClient client = new SocketClient("127.0.0.1", 9999);
        client.sendBytes(new byte[]{0x00});
        // 关闭会话，待所有线程处理结束后
        client.getConnector().dispose(true);
    }

    public IoConnector getConnector() {
        return connector;
    }

    @Override
    public void messageReceived(IoSession iosession, Object message) throws Exception {
        IoBuffer bbuf = (IoBuffer) message;
        byte[] byten = new byte[bbuf.limit()];
        bbuf.get(byten, bbuf.position(), bbuf.limit());
        logger.debug("客户端收到消息 {}", byten);
        logger.debug("客户端收到消息 {}", StringKit.bytes2hexString(byten));
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        logger.debug("客户端异常");
        super.exceptionCaught(session, cause);
    }

    @Override
    public void messageSent(IoSession iosession, Object obj) throws Exception {
        logger.debug("客户端消息发送 {}", obj);
        super.messageSent(iosession, obj);
    }

    @Override
    public void sessionClosed(IoSession iosession) throws Exception {
        logger.debug("客户端会话关闭");
        super.sessionClosed(iosession);
    }

    @Override
    public void sessionCreated(IoSession iosession) throws Exception {
        logger.debug("客户端会话创建");
        super.sessionCreated(iosession);
    }

    @Override
    public void sessionIdle(IoSession iosession, IdleStatus idlestatus)
            throws Exception {
        logger.debug("客户端会话休眠");
        super.sessionIdle(iosession, idlestatus);
    }

    @Override
    public void sessionOpened(IoSession iosession) throws Exception {
        logger.debug("客户端会话打开");
        super.sessionOpened(iosession);
    }
}
